package cn.zkteco.doordu.utils;

import android.content.Context;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by Jin on 2017/10/23.
 */

public class FileUtil {

    /**
     * 获取bin文件内的字节
     *
     * @param context
     * @param fileName
     * @return file bytes
     */
    public static byte[] getBytesFromAssets(Context context, String fileName) {
        byte[] buffer;
        try {
            InputStream in = context.getResources().getAssets().open(fileName);
            //获取文件的字节数
            int length = in.available();
//            int packages = length / 16;
            //创建byte数组
            buffer = new byte[length];
            //将文件中的数据读到byte数组中
            in.read(buffer);
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取文件的MD5值
     *
     * @param fileName
     * @return file md5 value
     */
    public static byte[] getFileMD5(Context context,String fileName) {

        byte[] b = getBytesFromAssets(context,fileName);
        byte[] md5;
        try {
            MessageDigest messageDigest =MessageDigest.getInstance("MD5");
            md5 = messageDigest.digest(b);
            return md5;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }


    }

    public static String getMd5(File file) throws FileNotFoundException {
        String value = null;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            BigInteger bi = new BigInteger(1, md5.digest());
            value = bi.toString(16);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return value;
    }


}
